
var step5=new Object();
step5.roles="";
step5.roles1 = []
step5.users = []
step5.projectTypeNo = $("#projectTypeNo").val();
step5.projectId = $("#projectId").val();
step5.projectStatus = $("#projectStatus").val();
step5.examPermission = $("#examPermission").val();
step5.maxClassHourRoleId = $("#maxClassHourRoleId").val();

    step5.init=function(basePath,page1,options){
       step5.basePath=basePath;
        step5.page=page1;
        //含有培训的
        step5.permissionTrain=options.permissionTrain;
        //含有考试的
        step5.permissionExam=options.permissionExam;
        //含有练习的
        step5.permissionExercise=options.permissionExercise;
        if(!step5.permissionExam){
          $("#next").html("<span class='fa fa-paper-plane'></span> 保存");
        }
        //选择受训角色
        step5.initRole();
        //step5.initProjectUser();
        //对于课程和人员的操作
        step5.handleSwitch();
    }

   //初始化受训角色
    step5.initRole=function() {
        $.ajax({
            url: appPath + '/admin/project/advanceSetting/getProjectRole',
            dataType: 'json',
            type:'get',
            data:{"projectId":step5.projectId},
            success:function (data) {
                var list = data;
                step5.roles = list;
                // 查询用户角色数据
                step5.initProjectUser();

            }

        })

     }

        //初始化用户角色数据
        step5.initProjectUser = function() {
            $.ajax({
                url: appPath + '/admin/project/advanceSetting/getProjectUser',
                dataType: 'json',
                type:'get',
                data:{"projectId":step5.projectId},
                success:function (data) {
                    var list = data;
                    list.forEach(function (e) {
                      if("-1" != e.role_id ){
                          step5.users.push(e);
                      }
                    });
                    // 展示用户角色列表数据
                    step5.project_user();
                    console.log("元数据=="+step5.users)
                }

            })

        }

    //刷新项目人员
    step5.project_user = function () {
        console.log(step5.users.length);
        var page_size = 10;
        var user_list_url = appPath + "/admin/project/advanceSetting/user_role";
        step5.page.init("select_user_form", user_list_url, "select_user_role", "select_user_page", 1, page_size);
        step5.page.goPage(1);
        step5.page.list = function(dataList){
            $(".switchAll").addClass("on");
            var len = dataList.length;
            var inner = "", item,role;
            // 组装数据
            var userInfoInner = "";
            for(var i=0; i< len; i++) {
                item = dataList[i];

                userInfoInner += '<tr >';
                userInfoInner += '<td><span class="text-orange tooltip" data-length="6">'+item['user_name']+'</span>';
                userInfoInner += '</td>';
                userInfoInner += '</tr>';
                if(step5.roles.length > 6){
                    inner += '<tr style="display: -webkit-flex;">';
                }else{
                    inner += '<tr>';
                }
                inner +='<input type="hidden" id="userId" value="'+ item['user_id'] +'"/>';
                // 判断该用户是否已分配角色
                var isSet = step5.isSetRole(item.user_id,item.role_id);
                // 比对roleId返回角标，用于判断是否禁止开关(进行中的项目，且开关已开需禁止开关)true允许点击，false需要禁止
                var flag = step5.select_on(step5.roles,item);
                for(var j=0; j < step5.roles.length; j++){
                    role = step5.roles[j];
                    // 已分配角色
                    if(isSet){

                        var index = step5.select(role.roleId,step5.roles,item);
                        // 该学员已分配角色(step5.ishave()该方法是用于数据回县，上一页下一页之间的数据回显)
                        if(index != "-1" ){
                            // 进行中的项目需禁止开关按钮
                            if(!flag){
                                inner += '<td width="150px;"><div class="on switch switch_btn selected switch_index switch_'+ j +'" data-roleId="'+ role.roleId +'"  data-roleName="'+ role.roleName +'" data-cellIndex="'+ j +'" data-rowIndex="'+ i +'"><span></span></div></td>';
                            }else{
                                inner += '<td width="150px;"><div class="on switch switch_btn switch_index switch_'+ j +'" data-roleId="'+ role.roleId +'"  data-roleName="'+ role.roleName +'" data-cellIndex="'+ j +'" data-rowIndex="'+ i +'" onclick="step5.switch(this);"><span></span></div></td>';
                            }
                        }else {

                            if (!flag) {
                                inner += '<td width="150px;"><div class="switch switch_btn switch_index switch_' + j + '" data-roleId="' + role.roleId + '"  data-roleName="' + role.roleName + '" data-cellIndex="' + j + '" data-rowIndex="' + i + '"><span></span></div></td>';
                            } else {
                                inner += '<td width="150px;"><div class="switch switch_btn switch_index switch_' + j + '" data-roleId="' + role.roleId + '"  data-roleName="' + role.roleName + '" data-cellIndex="' + j + '" data-rowIndex="' + i + '" onclick="step5.switch(this);"><span></span></div></td>';
                            }

                        }
                        if ($("#switch-" + role.roleId).hasClass("on")) {
                            $("#switch-" + role.roleId).removeClass("on");
                        }
                    }else{ // 未分配角色

                        // 该学员没有分配任何角色，默认给予学时最多的一个角色
                        if ( role.roleId == step5.maxClassHourRoleId) {
                            inner += '<td width="150px;"><div class="on switch switch_btn switch_index switch_' + j + '" data-roleId="' + role.roleId + '"  data-roleName="' + role.roleName + '" data-cellIndex="' + j + '" data-rowIndex="' + i + '" onclick="step5.switch(this);"><span></span></div></td>';
                            step5.repeatUserRole(item.user_id, role.roleId, role.roleName, step5.users);
                        } else {
                            inner += '<td width="150px;"><div class="switch switch_btn switch_index switch_' + j + '" data-roleId="' + role.roleId + '"  data-roleName="' + role.roleName + '" data-cellIndex="' + j + '" data-rowIndex="' + i + '" onclick="step5.switch(this);"><span></span></div></td>';
                            if ($("#switch-" + role.roleId).hasClass("on")) {
                                $("#switch-" + role.roleId).removeClass("on");
                            }
                        }
                    }

                }

                inner += '</tr>';
            }
            if('3' == step5.projectStatus){

            }
            $("#select_user").html(userInfoInner)
            return inner;
        }
    };
        //比对roleId返回角标，用于判断是否打开开关
        step5.select =function (roleId,roles,item) {
            var index = -1;
            step5.users.forEach(function (value) {
                if(value.roleId == roleId && value.userId == item.user_id){
                    index = 1;
                    return index;
                }
            });
            return index;
        }

        //比对roleId返回角标，用于判断是否禁闭开关
        step5.select_on = function (roles,item) {
          var flag = true;
          if('3' == step5.projectStatus){
            for(var i=0;i<roles.length;i++){
              var role = roles[i];
              if(role.roleId == item['role_id'] ){
                flag = false;
                break;
              }
            }
          }
          return flag;
        };

   // 判断用户是否已分配角色
    step5.isSetRole = function(userId,roleId,roles){
        var isSet = false;
        step5.users.forEach(function (value) {
            if(value.userId == userId ){
                step5.roles.forEach(function (e) {
                  if(value.roleId == e.roleId){
                      isSet = true;
                      return isSet;
                  }
                });

            }
        });

        return isSet;
    };


//开关事件
    step5.switch = function (obj) {
        $(obj).toggleClass('on');
        var rowIndex = $(obj).attr('data-rowIndex');
        var cellIndex = $(obj).attr('data-cellIndex');
        //添加用户数据到step5.users数组中
        if($(obj).hasClass("on")){
            step5.saveUserRole(obj);
        }else{
            step5.removeUserRole(obj)
        }
        //做成单选
        //一行内只能有一个选中
        var flag=false;
        $.each($(".switch[data-cellIndex!="+cellIndex+"][data-rowIndex="+rowIndex+"]"),function (i,e) {
            if($(this).hasClass("on")){
                flag=true
            }
        })
        if(flag){
            $(".switch[data-cellIndex!="+cellIndex+"][data-rowIndex="+rowIndex+"]").removeClass("on");
        }

        //一列内没有选中，表头选中要去掉
        var flag1=true;
        $.each($("#select_user_role .switch[data-cellIndex="+cellIndex+"]"),function (i,e) {
            if(!$(this).hasClass("on")){
                flag1=false;
            }
        })
        if(!flag1){
            //$(".switchAll[data-index="+cellIndex+"]").removeClass("on");
          $(".switchAll").removeClass("on");
        }else{
            $(".switchAll[data-index="+cellIndex+"]").addClass("on");
        }

    }

        //开关相关事件
        step5.handleSwitch=function () {
            //全开全关
            $('.switchAll').on('click',function(){
                // 列的角标位置
              var index = $(this).attr('data-index');
              // 所有的子开关是否是已打开状态
              var flag = $(".switch[data-cellIndex="+index+"]").hasClass("selected");
              // 当前列的总开关是否已打开状态
              var flag_ = $(this).hasClass("on");
              var len = step5.roles.length;
              if(flag){
                  if(len>1 && !flag_){
                    $(this).removeClass("on");
                  }else{
                    $(this).addClass("on");
                  }
              }else{
                $(this).toggleClass("on");
              }
              if($(this).hasClass("on")){
                $(".switch_"+index).addClass("on");
                $(".switch[data-cellIndex!="+index+"]").removeClass("on");
                  $(".switchAll[data-index!="+index+"]").removeClass("on");
              }else{
                  if(!flag){
                    $(".switch_"+index).removeClass("on");
                  }
              }

              $.each($("#select_user_role .switch_"+ index ),function (index,element) {
                if($(this).hasClass("on")){
                  step5.saveUserRole(this);
                }else{
                  step5.removeUserRole(this);
                }
              })
            })

            $.each($("#select_user_role .switch"),function (index,element) {
                var cellIndex=$(obj).attr('data-cellIndex');

            });

            // 根据用户名称查询
            $("#btn_search_user").click(function(){
                $("#userName").val($.trim($("#userName").val()));
                step5.project_user()
            });
            //查询所有
            $("#btn_search_all_user").click(function(){
                $("#userName").val('');
                step5.project_user();

            });

            //回到首页
            $("#index").click(function () {
                var operType = "index";
                if(step5.users.length > 0){
                    layer.confirm('是否保存已配置的人员角色信息?', {btn: ['是','否'],icon:3}, function(index){
                        //发布项目
                        step5.next(operType);
                    },function(){
                        window.location.href = appPath + "/admin";
                    });
                }else{
                    window.location.href = appPath + "/admin";
                }
            });


            //上一步操作
            $("#pev").click(function () {
                var redirect_url = appPath + "/admin/project/advanceSetting/step4?projectTypeNo="+step5.projectTypeNo+"&projectId="+step5.projectId+"&projectStatus="+step5.projectStatus+"&examPermission="+step5.examPermission;
                var operType = "prev";
                if(step5.users.length > 0){
                    layer.confirm('是否保存已配置的人员角色信息?', {btn: ['是','否'],icon:3}, function(index){
                        //发布项目
                        step5.next(operType);
                    },function(){
                        window.location.href = redirect_url
                    });
                }else{
                    window.location.href = redirect_url
                }
            })
            //下一步操作
            $("#next").click(function () {
                if(step5.users.length < step5.page.count){
                    layer.msg('还有人员未分配角色，请先分配',{time : 2000});
                    return;
                }

                    step5.next();
            })

        };


        //下一步取值
        step5.next = function(operType){
           /* var roles=[];
            var users=[]
            $.each($("#select_user_role .on"),function (index,element) {

                var role=new Object();
                role.roleId=$(this).attr('data-roleId');
                role.roleName=$(this).attr('data-roleName');
                console.log(role);
                //判重
                if(step5.repeat(role.roleId,roles)){
                    roles.push(role);
                }


                var user=new Object();
                var $tr = $(this).parent().parent()
                var $td = $(this).parent().parent().find("td:eq(0)");
                user.userId= $td.children("input").val();
                user.roleId = role.roleId;
                //添加到数组
                users.push(user);

            })*/
           //获取角色
            step5.getRoles();
            console.log("角色======"+step5.roles1);
            console.log("用户======"+step5.users);
            if(step5.roles1.length==0){
                var isRegistration=$("#isRegistration").val();
                if (isRegistration=='2') {
                    layer.msg("请给人员分配角色");
                    return;
                }
            }
            var params={
                "roles":JSON.stringify(step5.roles1),
                "users":JSON.stringify(step5.users),
                "projectId":step5.projectId,
                "projectType":step5.projectTypeNo
            }
            //保存数据
            step5.save(params,operType);
        }
        //发送异步保存信息
        step5.save = function (params,operType) {
            $.ajax({
                dataType: 'json',
                url: appPath + '/admin/project/advanceSetting/user_role_update',
                async: false,
                type: 'post',
                data:params,
                success:function (data) {
                    var code = data.code;
                    if(10000 == code){
                        // 回到首页
                      if("index" == operType){
                          window.location.href = appPath + "/admin";
                          return;
                          // 回到上一页
                      }else if("prev" == operType){
                          window.location.href = appPath + "/admin/project/advanceSetting/step4?projectTypeNo="+step5.projectTypeNo+"&projectId="+step5.projectId+"&projectStatus="+step5.projectStatus+"&examPermission="+step5.examPermission;
                          return;
                      }else{

                          if(step5.permissionExam){
                              window.location.href = appPath + "/popup/project_create/step6?projectTypeNo="+step5.projectTypeNo+"&projectId="+step5.projectId+"&source=step5"+"&projectStatus="+step5.projectStatus+"&examPermission="+step5.examPermission;;
                          }else{
                              if(step5.projectStatus == '1'){
                                  layer.confirm('是否发布', {btn: ['是','否']}, function(index){
                                      // 发布项目
                                      step5.releaseProject();
                                  },function(){
                                      window.location.href = appPath + "/admin";
                                  });
                              }else{
                                  window.location.href = appPath + "/admin";
                              }
                          }
                      }


                    }
                }
            })
        }

        //缓存用户角色信息
        step5.saveUserRole = function (obj) {
            var role = new Object();
            role.roleId=$(obj).attr('data-roleId');
            role.roleName=$(obj).attr('data-roleName');
            console.log(role);

            var user=new Object();
            /*var $td = $(obj).parent().parent().find("td:eq(0)");
            user.userId = $td.children("input").val();*/

            var $tr = $(obj).parent().parent();
            user.userId = $tr.find("input").val();
            //判重并添加数据
            step5.repeatUserRole(user.userId,role.roleId,role.roleName,step5.users)


        }

        //去除用户角色信息
        step5.removeUserRole = function (obj) {

            var role = new Object();
            role.roleId = $(obj).attr('data-roleId');
            role.roleName = $(obj).attr('data-roleName');
            console.log(role);

            var user = new Object();
           // var $td = $(obj).parent().parent().find("td:eq(0)");
            //user.userId= $td.children("input").val();
            var $tr = $(obj).parent().parent();
            user.userId = $tr.find("input").val();
            user.roleId = role.roleId;

            for (var j=0;j<step5.users.length;j++){
                if(step5.users[j].userId == user.userId && step5.users[j].roleId == role.roleId){
                    step5.users.splice(j,1);
                }
            }

        }


        //去除重复的受训角色
        step5.repeatRole=function(id,roles){
            var flag=true;
            for (var i=0;i<roles.length;i++){
                if(roles[i].roleId==id){
                    flag=false;
                }
            }
            return flag;
        }
        //去除重复的用户受训角色
        step5.repeatUserRole = function(userId,roleId,roleName,users){
            var flag = true;
            for (var i=0;i<users.length;i++){
                if(users[i].userId == userId ){
                    users[i].roleId = roleId;
                    users[i].roleName = roleName;
                    flag=false;
                }
            }
            if(flag){
                var user = new Object();
                user.userId= userId
                user.roleId = roleId;
                user.roleName = roleName;
                step5.users.push(user);
            }
        }

        //获取角色数组
        step5.getRoles=function () {
            step5.roles1 = [];
            for(var i=0;i < step5.users.length ;i++){
                if(step5.repeatRole(step5.users[i].roleId,step5.roles1)){
                    var role = new Object();
                    role.roleId = step5.users[i].roleId
                    role.roleName = step5.users[i].roleName;
                    step5.roles1.push(role);
                }
            }
        }

        //发布项目
        step5.releaseProject=function(){

                var projectStatus = "2";
                $.ajax({
                    dataType: 'json',
                    url: appPath + '/admin/project_create/private/publish_project',
                    async: false,
                    type: 'post',
                    data: {
                        'projectId': $("#projectId").val(),
                        'projectStatus': projectStatus
                    },
                    success: function(data){
                        var code = data['code'];
                        if(code==10000){
                                // 返回首页
                                layer.msg("发布成功");
                                window.location.href=appPath+ "/admin";
                        }else{
                            layer.alert('操作失敗', {icon: 2,  skin: 'layer-ext-moon'});
                        }
                    }
                });
        };